Explain Slices in Go Programming Language | Go Programming Tutorial
In this article, you will learn:
- What are Slices in Go Programming Language?
- How to declare the Slice?
- What are the components of Slice?
What are Slices in Go Programming Language?
In GoLang, a slice is very powerful, flexible, and more convenient than an array. It is a lightweight data structure. A slice is a long sequence that is used to store the different types of elements in the same slice. It is similar to an array which has an index value and length. But the difference between the size of the size is resized, they are not of fixed length like an array. However, the slice and an array are connected. Slice allowed to store duplicate elements in the slice. The first position in the slice is always 0 and the last index of the slice will be (length of slice -1).
Declaration of Slice
A slice is declared just like an array, but it does not have the length of the slice. So, it can grow or shrink according to the requirement.
[ ]T
or
[ ] T{ }
or
[ ] T{value1, value2, value3, ….. value n}
Here, T represents the type of elements.
var my_slice[ ] int
Components of Slice
A slice contains three components:
- Pointer: The pointer is used to point to the first element of the array that is accessible through the slice. Here, the pointed element don't need to be the first element of the array.
- Length: The length equals the total number of elements present in the array.
- Capacity: The capacity represents the maximum size upto which it can expand.
Example:
package mainimport "fmt"func main() { // Creating an array in GoLang ar := [ 5]string{"This", "is", "the", "tutorials", "link"} // Display array in GoLang fmt.Println("Array:", ar) // Creating a slice in GoLang slice_ele := ar[1: 3] // Display slice fmt.Println("Slice:", slice_ele) // Display length of the slice fmt.Printf("Length of the slice: %d", len(slice_ele)) // Display the capacity of the slice fmt.Printf("\nCapacity of the slice: %d", cap(slice_ele))}Output:
Array: [This is the tutorials link]
Slice: [ is the tutorials]
Length of the slice: 3
Capacity of the slice: 4


